package com.cmall.common.foundation.util;

import org.apache.commons.lang3.StringUtils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 提供对日期时间操作的常用方法
 */
public class DateUtil {
	private static final long ONE_DAY = 24 * 3600000;

	private static final long ONE_MINUTE = 60000;

	private static String datePattern = "yyyy-MM-dd";

	public  static  final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";

	private static String monthPattern = "yyyy-MM";

	private static String yearPattern = "yyyy";

	private static String timePattern = "HH:mm:ss";

	private static String millisecondPattern = ".SSS";

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			datePattern);

	private static SimpleDateFormat datetimeFormat = new SimpleDateFormat(
			datePattern + " " + timePattern);

	private static SimpleDateFormat timeStampFormat = new SimpleDateFormat(
			datePattern + " " + timePattern + millisecondPattern);

	private static SimpleDateFormat monthFormat = new SimpleDateFormat(
			monthPattern);

	private static SimpleDateFormat yearFormat = new SimpleDateFormat(
			yearPattern);

	/**
	 * 将日期对象转换为字符串，格式为yyyy-MM-dd
	 * 
	 * @param date
	 *            日期
	 * @return 日期对应的日期字符串
	 */
	public static String toDateString(Date date) {
		if (date == null) {
			return null;
		}
		return dateFormat.format(date);
	}

	/**
	 * 取得指定日期格式的字符串
	 *
	 * @param Date
	 * @return String
	 */
	public static String formatDate(Date date, String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}

	/**
	 * 将字符串转换为日期对象，字符串必须符合yyyy-MM-dd的格式
	 * 
	 * @param s
	 *            要转化的字符串
	 * @return 字符串转换成的日期.如字符串为NULL或空串,返回NULL
	 */
	public static Date toDate(String s) {
		s = StringUtils.trim(s);
		if (s.length() < 1) {
			return null;
		}
		try {
			if (s.length() <= 10) {
				return dateFormat.parse(s);
			}
			return toDate(Timestamp.valueOf(s));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 将字符串转换为日期对象，字符串必须符合yyyy-MM-dd HH:mm:ss.SSS的格式
	 * 
	 * @param s
	 *            要转化的字符串
	 * @return 字符串转换成的日期.如字符串为NULL或空串,返回NULL
	 */
	public static Date toDateTimeFromString(String s) {
		s = StringUtils.trim(s);
		if (s.length() < 1) {
			return null;
		}
		try {
			if (s.length() <= 10) {
				return datetimeFormat.parse(s);
			}
			return toDate(Timestamp.valueOf(s));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 将日期对象转换为字符串，转换后的格式为yyyy-MM-dd HH:mm:ss
	 * 
	 * @param date
	 *            要转换的日期对象
	 * @return 字符串,格式为yyyy-MM-dd HH:mm:ss
	 */
	public static String toDatetimeString(Date date) {
		if (date == null) {
			return null;
		}
		return datetimeFormat.format(date);
	}

	/**
	 * 将日期对象转换为字符串，转换后的格式为yyyy-MM-dd HH:mm:ss.SSS
	 * 
	 * @param date
	 *            要转换的日期对象
	 * @return 字符串,格式为yyyy-MM-dd HH:mm:ss.SSS
	 */
	public static String toTimeStampString(Date date) {
		if (date == null) {
			return null;
		}
		return timeStampFormat.format(date);
	}

	/**
	 * 将日期对象转换为字符串，转换后的格式为yyyy-MM-dd HH:mm:ss.SSS
	 * 
	 * @param date
	 *            要转换的日期对象
	 * @return 字符串,格式为yyyy-MM-dd HH:mm:ss.SSS
	 */
	public static Date toDatetime(String date) {
		if (date == null) {
			return null;
		}
		try {
			return timeStampFormat.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 计算两个日期间相隔的周数
	 * 
	 * @param startDate
	 *            开始日期
	 * @param endDate
	 *            结束日期
	 * @return
	 */
	public static int computeWeek(Date startDate, Date endDate) {

		int weeks = 0;

		Calendar beginCalendar = Calendar.getInstance();
		beginCalendar.setTime(startDate);

		Calendar endCalendar = Calendar.getInstance();
		endCalendar.setTime(endDate);

		while (beginCalendar.before(endCalendar)) {

			// 如果开始日期和结束日期在同年、同月且当前月的同一周时结束循环
			if (beginCalendar.get(Calendar.YEAR) == endCalendar
					.get(Calendar.YEAR)
					&& beginCalendar.get(Calendar.MONTH) == endCalendar
							.get(Calendar.MONTH)
					&& beginCalendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) == endCalendar
							.get(Calendar.DAY_OF_WEEK_IN_MONTH)) {
				break;

			} else {

				beginCalendar.add(Calendar.DAY_OF_YEAR, 7);
				weeks += 1;
			}
		}

		return weeks;
	}

	/**
	 * 返回当前系统时间
	 * 
	 * @return
	 */
	public static String getCurrDateTime() {
		return toDatetimeString(new Date());

	}

	/**
	 * 获取系统当前时间，待后期可扩展到取数据库时间
	 * 
	 * @return 系统当前时间
	 */
	public static String getCurrDate() {
		return toDateString(new Date());

	}

	/**
	 * 将Timestamp转换为日期
	 * 
	 * @param timestamp
	 *            时间戳
	 * @return 日期对象.如时间戳为NULL,返回NULL
	 */
	public static Date toDate(Timestamp timestamp) {
		if (timestamp == null) {
			return null;
		}
		return new Date(timestamp.getTime());
	}

	/**
	 * 将日期转换为Timestamp
	 * 
	 * @param date
	 *            日期
	 * @return 时间戳.如日期为NULL,返回NULL
	 */
	public static Timestamp toTimestamp(Date date) {
		if (date == null) {
			return null;
		}

		return new Timestamp(date.getTime());
	}

	/**
	 * 将时间戳对象转化成字符串
	 * 
	 * @param t
	 *            时间戳对象
	 * @return 时间戳对应的字符串.如时间戳对象为NULL,返回NULL
	 */
	public static String toDateString(Timestamp t) {
		if (t == null) {
			return null;
		}
		return toDateString(toDate(t));
	}

	/**
	 * 将Timestamp转换为日期时间字符串
	 * 
	 * @param t
	 *            时间戳对象
	 * @return Timestamp对应的日期时间字符串.如时间戳对象为NULL,返回NULL
	 */
	public static String toDatetimeString(Timestamp t) {
		if (t == null) {
			return null;
		}
		return toDatetimeString(toDate(t));
	}

	/**
	 * 将日期字符串转换为Timestamp对象
	 * 
	 * @param s
	 *            日期字符串
	 * @return 日期时间字符串对应的Timestamp.如字符串对象为NULL,返回NULL
	 */

	public static Timestamp toTimestamp(String s) {
		return toTimestamp(toDate(s));
	}

	/**
	 * 返回年份，如2014
	 * */
	public static int getYear(Date d) {

		Calendar c = Calendar.getInstance();
		c.setTime(d);
		return c.get(Calendar.YEAR);
	}

	public static int getYear() {
		return getYear(new Date());
	}

	/**
	 * 返回月份，为1－－ － 12内
	 * */
	public static int getMonth(Date d) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		return c.get(Calendar.MONTH) + 1;
	}

	public static int getMonth() {
		return getMonth(new Date());
	}

	/**
	 * 取得季度
	 * 
	 * @param d
	 *            日期类型
	 * @return
	 */
	public static final int getQuarter(Date d) {
		return getQuarter(getMonth(d));
	}

	/**
	 * 取得当前的季度
	 * 
	 * @return
	 */
	public static final int getQuarter() {
		return getQuarter(getMonth());
	}

	/**
	 * 传递月份,取得季度
	 * 
	 * @param num
	 * @return
	 */
	public static final int getQuarter(int num) {
		num = num % 3 == 0 ? num / 3 : (num / 3 + 1);
		return num % 4 == 0 ? 4 : num % 4;

	}

	/**
	 * 返回日期，为1－－ － 31内
	 * */
	public static int getDay(Date d) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		return c.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 获得将来的日期.如果timeDiffInMillis > 0,返回将来的时间;否则，返回过去的时间
	 * 
	 * @param currDate
	 *            现在日期
	 * @param timeDiffInMillis
	 *            毫秒级的时间差
	 * @return 经过 timeDiffInMillis 毫秒后的日期
	 * */
	public static Date getFutureDate(Date currDate, long timeDiffInMillis) {
		long l = currDate.getTime();

		l += timeDiffInMillis;
		return new Date(l);
	}

	/**
	 * 获得将来的日期.如果timeDiffInMillis > 0,返回将来的时间;否则，返回过去的时间
	 * 
	 * @param currDate
	 *            现在日期
	 * @param timeDiffInMillis
	 *            毫秒级的时间差
	 * @return 经过 timeDiffInMillis 毫秒后的日期
	 * */
	public static Date getFutureDate(String currDate, long timeDiffInMillis) {
		return getFutureDate(toDate(currDate), timeDiffInMillis);
	}

	/**
	 * 获得将来的日期.如果 days > 0,返回将来的时间;否则，返回过去的时间
	 * 
	 * @param currDate
	 *            现在日期
	 * @param days
	 *            经过的天数
	 * @return 经过days天后的日期
	 * */
	public static Date getFutureDate(Date currDate, int days) {
		long l = currDate.getTime();
		long l1 = (long) days * ONE_DAY;

		l += l1;
		return new Date(l);
	}

	/**
	 * 获得将来的日期.如果 days > 0,返回将来的时间;否则，返回过去的时间
	 * 
	 * @param currDate
	 *            现在日期,字符型如2005-05-05 [14:32:10]
	 * @param days
	 *            经过的天数
	 * @return 经过days天后的日期
	 * */
	public static Date getFutureDate(String currDate, int days) {
		return getFutureDate(toDate(currDate), days);
	}

	/**
	 * 检查是否在核算期内
	 * 
	 * @param currDate
	 *            当前时间
	 * @param dateRange
	 *            核算期日期范围
	 * @return 是否在核算期内
	 * */
	public static boolean isDateInRange(String currDate, String[] dateRange) {
		if (currDate == null || dateRange == null || dateRange.length < 2) {
			throw new IllegalArgumentException("传入参数非法");
		}

		currDate = getDatePart(currDate);
		return (currDate.compareTo(dateRange[0]) >= 0 && currDate
				.compareTo(dateRange[1]) <= 0);
	}

	/**
	 * 只获取日期部分.获取日期时间型的日期部分
	 * 
	 * @param currDate
	 *            日期[时间]型的字串
	 * @return 日期部分的字串
	 * */
	public static String getDatePart(String currDate) {
		if (currDate != null && currDate.length() > 10) {
			return currDate.substring(0, 10);
		}

		return currDate;
	}

	/**
	 * 计算两天的相差天数,不足一天按一天算
	 * 
	 * @param stopDate
	 *            结束日期
	 * @param startDate
	 *            开始日期
	 * @return 相差天数 = 结束日期 - 开始日期
	 * */
	public static int getDateDiff(String stopDate, String startDate) {
		long t2 = toDate(stopDate).getTime();
		long t1 = toDate(startDate).getTime();

		int diff = (int) ((t2 - t1) / ONE_DAY); // 相差天数
		// 如有剩余时间，不足一天算一天
		diff += (t2 > (t1 + diff * ONE_DAY) ? 1 : 0);
		return diff;
	}

	/**
	 * 计算两天的相差分钟,不足一分钟按一分钟算
	 * 
	 * @param stopDate
	 *            结束日期
	 * @param startDate
	 *            开始日期
	 * @return 相差分钟数 = 结束日期 - 开始日期
	 * */
	public static int getMinutesDiff(String stopDate, String startDate) {
		long t2 = toDate(stopDate).getTime();
		long t1 = toDate(startDate).getTime();

		int diff = (int) ((t2 - t1) / ONE_MINUTE); // 相差分钟数
		// 如有剩余时间，不足一天算一天
		diff += (t2 > (t1 + diff * ONE_MINUTE) ? 1 : 0);
		return diff;
	}

	/**
	 * 判断两个日期是否在同一周
	 */
	public static boolean isSameWeekDates(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		Calendar cal2 = Calendar.getInstance();
		cal1.setFirstDayOfWeek(Calendar.MONDAY);
		cal2.setFirstDayOfWeek(Calendar.MONDAY);
		cal1.setTime(date1);
		cal2.setTime(date2);
		int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
		if (0 == subYear) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
					.get(Calendar.WEEK_OF_YEAR))
				return true;
		} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
			// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
					.get(Calendar.WEEK_OF_YEAR))
				return true;
		} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
					.get(Calendar.WEEK_OF_YEAR))
				return true;
		}
		return false;
	}

	/**
	 * 
	 * 按年获取周序号
	 * 
	 * @param currDate
	 * @return
	 */
	public static int getSeqWeekByYear(Date currDate) {
		Calendar c = Calendar.getInstance();
		c.setTime(currDate);
		c.setFirstDayOfWeek(Calendar.MONDAY);
		int weekNo = c.get(Calendar.WEEK_OF_YEAR);

		Calendar lastDate = Calendar.getInstance();

		if (weekNo == 1) {
			// 获取周五时间
			lastDate.setTime(DateUtil.toDate(getFriday(c.getTime())));
			if (c.get(Calendar.YEAR) != lastDate.get(Calendar.YEAR)) {
				lastDate.setTime(DateUtil.toDate(getMonday(c.getTime())));
				lastDate.add(Calendar.DATE, -1);
				lastDate.setFirstDayOfWeek(Calendar.MONDAY);
				weekNo = lastDate.get(Calendar.WEEK_OF_YEAR) + 1;
			}
		}
		return weekNo;
	}

	/**
	 * 
	 * 按月获取周序号
	 * 
	 * @param currDate
	 * @return
	 */
	public static int getSeqWeekByMonth(Date currDate) {
		Calendar c = Calendar.getInstance();
		c.setTime(currDate);
		c.setFirstDayOfWeek(Calendar.MONDAY);

		return c.get(Calendar.WEEK_OF_MONTH);
	}

	/**
	 * 
	 * 获取周一的日期
	 * 
	 * @param date
	 * @return
	 */
	public static String getMonday(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}

	/**
	 * 
	 * 获取周一的日期
	 * 
	 * @param date
	 * @return
	 */
	public static String getMonday(String date) {
		Calendar c = Calendar.getInstance();
		c.setTime(toDate(date));
		c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}

	/**
	 * 获得周五的日期
	 */
	public static String getFriday(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}

	// 当前日期前几天或者后几天的日期
	public static String afterNDay(int n) {
		Calendar c = Calendar.getInstance();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		c.setTime(new Date());
		c.add(Calendar.DATE, n);
		Date d2 = c.getTime();
		String s = df.format(d2);
		return s;
	}

	/**
	 * 获取前或后几个小时的日期
	 * 
	 * @param h
	 *            小时(正数为过去;负数为将来)
	 * 
	 * @return Date日期
	 */
	public static Date afterNHour(int h) {
		Calendar expireDate = Calendar.getInstance();
		expireDate.set(Calendar.HOUR_OF_DAY,
				expireDate.get(Calendar.HOUR_OF_DAY) - h);
		return expireDate.getTime();
	}

	/**
	 * 判断某年是否为闰年
	 * 
	 * @return boolean
	 * 
	 */
	public static boolean isLeapYear(int yearNum) {
		boolean isLeep = false;
		/** 判断是否为闰年，赋值给一标识符flag */
		if ((yearNum % 4 == 0) && (yearNum % 100 != 0)) {
			isLeep = true;
		} else if (yearNum % 400 == 0) {
			isLeep = true;
		} else {
			isLeep = false;
		}
		return isLeep;
	}

	/**
	 * 计算某年某周的开始日期
	 * 
	 * @return interger
	 * 
	 */
	public static String getYearWeekFirstDay(int yearNum, int weekNum) {

		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		cal.set(Calendar.YEAR, yearNum);
		cal.set(Calendar.WEEK_OF_YEAR, weekNum);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		// 分别取得当前日期的年、月、日
		String tempYear = Integer.toString(yearNum);
		String tempMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
		String tempDay = Integer.toString(cal.get(Calendar.DATE));
		String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
		return SetDateFormat(tempDate, "yyyy-MM-dd");
	}

	/**
	 * @see 取得指定时间的给定格式()
	 * @return String
	 * 
	 */
	public static String SetDateFormat(String myDate, String strFormat) {

		try {
			SimpleDateFormat sdf = new SimpleDateFormat(strFormat);
			String sDate = sdf.format(sdf.parse(myDate));
			return sDate;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 计算某年某周的结束日期
	 * 
	 * @return interger
	 * 
	 */
	public String getYearWeekEndDay(int yearNum, int weekNum) {

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, yearNum);
		cal.set(Calendar.WEEK_OF_YEAR, weekNum + 1);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		// 分别取得当前日期的年、月、日
		String tempYear = Integer.toString(yearNum);
		String tempMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
		String tempDay = Integer.toString(cal.get(Calendar.DATE));
		String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
		return SetDateFormat(tempDate, "yyyy-MM-dd");
	}

	/**
	 * 计算某年某月的开始日期
	 * 
	 * @return interger
	 * 
	 */
	public String getYearMonthFirstDay(int yearNum, int monthNum) {

		// 分别取得当前日期的年、月、日
		String tempYear = Integer.toString(yearNum);
		String tempMonth = Integer.toString(monthNum);
		String tempDay = "1";
		String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
		return SetDateFormat(tempDate, "yyyy-MM-dd");
	}

	/**
	 * 计算某年某月的结束日期
	 * 
	 * @return interger
	 * 
	 */
	public static String getYearMonthEndDay(int yearNum, int monthNum) {

		// 分别取得当前日期的年、月、日
		String tempYear = Integer.toString(yearNum);
		String tempMonth = Integer.toString(monthNum);
		String tempDay = "31";
		if (tempMonth.equals("1") || tempMonth.equals("3")
				|| tempMonth.equals("5") || tempMonth.equals("7")
				|| tempMonth.equals("8") || tempMonth.equals("10")
				|| tempMonth.equals("12")) {
			tempDay = "31";
		}
		if (tempMonth.equals("4") || tempMonth.equals("6")
				|| tempMonth.equals("9") || tempMonth.equals("11")) {
			tempDay = "30";
		}
		if (tempMonth.equals("2")) {
			if (isLeapYear(yearNum)) {
				tempDay = "29";
			} else {
				tempDay = "28";
			}
		}

		String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
		return tempDate;

	}

	/**
	 * 根据参数，获取相对日期
	 * 
	 * @param date
	 * @param flag
	 * @param intervals
	 * @return
	 */
	public static Date getRelativeDate(Date date, char flag, int intervals) {
		Date currDate = null;
		if (date != null) {
			Calendar newDate;
			(newDate = Calendar.getInstance()).setTime(date);
			switch (flag) {
			case 'y':
				newDate.add(Calendar.YEAR, intervals);
				break;
			case 'M':
				newDate.add(Calendar.MONTH, intervals);
				break;
			case 'd':
				newDate.add(Calendar.DATE, intervals);
				break;
			case 'w':
				newDate.add(Calendar.WEEK_OF_YEAR, intervals);
				break;
			case 'h':
				newDate.add(Calendar.HOUR, intervals);
				break;
			case 'm':
				newDate.add(Calendar.MINUTE, intervals);
				break;
			case 's':
				newDate.add(Calendar.SECOND, intervals);
				break;
			case 'S':
				newDate.add(Calendar.MILLISECOND, intervals);
			}
			currDate = newDate.getTime();
		}
		return currDate;
	}

	/**
	 * 获取当前日期
	 * 
	 * @return
	 */
	public static Date getCurrDay() {
		return new Date();
	}

	/**
	 * 获取下一周的第一天
	 * 
	 * @return
	 */
	public static String getAfterWeekFirst() {
		return getMonday(afterNDay(7));
	}

	/**
	 * 获取下一月的第一天
	 * 
	 * @param date
	 * @param afterNum
	 * @return
	 */
	public static String getAfterMonthFirst(String date, int afterNum) {
		Calendar cal = new GregorianCalendar();
		cal.setTime(toDate(date));
		cal.add(Calendar.MONTH, afterNum);
		cal.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		return dateFormat.format(cal.getTime());
	}

	/**
	 * 获取周日
	 * 
	 * @param date
	 * @param afterNum
	 * @return
	 */
	public static String getSundayOfWeek(String date) {
		Calendar cal = new GregorianCalendar();
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		cal.setTime(toDate(date));
		cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek() + 6);
		return dateFormat.format(cal.getTime());
	}

	/**
	 * 获取下一季度的第一天
	 * 
	 * @param date
	 * @param afterNum
	 * @return
	 */
	public static String getAfterQuarterFirst(String date, int afterNum) {
		Calendar cal = new GregorianCalendar();
		cal.setTime(toDate(date));
		int currentMonth = cal.get(Calendar.MONTH) + 1;
		cal.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		if (currentMonth >= 1 && currentMonth <= 3)
			cal.set(Calendar.MONTH, 0);
		else if (currentMonth >= 4 && currentMonth <= 6)
			cal.set(Calendar.MONTH, 3);
		else if (currentMonth >= 7 && currentMonth <= 9)
			cal.set(Calendar.MONTH, 6);
		else if (currentMonth >= 10 && currentMonth <= 12)
			cal.set(Calendar.MONTH, 9);
		cal.add(Calendar.MONTH, afterNum * 3);
		return dateFormat.format(cal.getTime());
	}

	public static String toDateFormate(Date date) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String time = sf.format(date);
		return time + "000000";
	}

	/**
	 * 计算两个日期间隔天数
	 * 
	 * @param smdate
	 * @param bdate
	 * @return
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	public static String getNowWeekBegin() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
		return df.format(cal.getTime());

	}

	public static String beforNumDay(Date date, int day) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DAY_OF_YEAR, day);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}

	public static String getNowMonthBegin() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}

	public static void main(String[] args) {
		System.out.println(getAfterWeekFirst());
	}

	/**
	 * 将英文星期转换成数字
	 * 
	 * @param masterWeek
	 */
	public static String getWeek(String masterWeek) {
		// 拼 week 字符串
		String weekStr;
		// 日
		if (masterWeek.indexOf("SUN") >= 0) {
			weekStr = "1";
		} else {
			weekStr = "0";
		}
		// 一
		if (masterWeek.indexOf("MON") >= 0) {
			weekStr = weekStr + "1";
		} else {
			weekStr = weekStr + "0";
		}
		// 二
		if (masterWeek.indexOf("TUE") >= 0) {
			weekStr = weekStr + "1";
		} else {
			weekStr = weekStr + "0";
		}
		// 三
		if (masterWeek.indexOf("WED") >= 0) {
			weekStr = weekStr + "1";
		} else {
			weekStr = weekStr + "0";
		}
		// 四
		if (masterWeek.indexOf("THU") >= 0) {
			weekStr = weekStr + "1";
		} else {
			weekStr = weekStr + "0";
		}
		// 五
		if (masterWeek.indexOf("FRI") >= 0) {
			weekStr = weekStr + "1";
		} else {
			weekStr = weekStr + "0";
		}
		// 六
		if (masterWeek.indexOf("SAT") >= 0) {
			weekStr = weekStr + "1";
		} else {
			weekStr = weekStr + "0";
		}
		return weekStr;
	}

	/**
	 * 统计两个日期之间的所有日期
	 * 
	 * @Title: getDates
	 * @Description:
	 * @param @param p_start
	 * @param @param p_end
	 * @param @return
	 * @data 2016年9月12日 下午2:25:16
	 * @throws
	 */
	public static List<String> getDates(Calendar p_start, Calendar p_end) {
		List<String> result = new ArrayList<String>();
		result.add(dateFormat.format(p_start.getTime()));
		Calendar temp = p_start;
		temp.add(Calendar.DATE, 1);
		while (temp.before(p_end)) {
			result.add(dateFormat.format(temp.getTime()));
			temp.add(Calendar.DATE, 1);
		}
		result.add(dateFormat.format(p_end.getTime()));
		return result;
	}

	/**
	 * 统计两个日期之间月份
	 * 
	 * @Title: getMonths
	 * @Description:
	 * @param @param p_start
	 * @param @param p_end
	 * @param @return
	 * @data 2016年9月12日 下午2:26:59
	 * @throws
	 */
	public static List<String> getMonths(Calendar p_start, Calendar p_end) {
		List<String> result = new ArrayList<String>();
		result.add(monthFormat.format(p_start.getTime()));
		Calendar temp = p_start;
		temp.add(Calendar.MONTH, 1);
		while (temp.before(p_end)) {
			result.add(monthFormat.format(temp.getTime()));
			temp.add(Calendar.MONTH, 1);
		}
		result.add(monthFormat.format(p_end.getTime()));
		return result;
	}

	/**
	 * 统计两个日期之间的年份
	 * 
	 * @Title: getYears
	 * @Description:
	 * @param @param p_start
	 * @param @param p_end
	 * @param @return
	 * @data 2016年9月12日 下午2:28:04
	 * @throws
	 */
	public static List<String> getYears(Calendar p_start, Calendar p_end) {
		List<String> result = new ArrayList<String>();
		result.add(yearFormat.format(p_start.getTime()));
		Calendar temp = p_start;
		temp.add(Calendar.YEAR, 1);
		while (temp.before(p_end)) {
			result.add(yearFormat.format(temp.getTime()));
			temp.add(Calendar.YEAR, 1);
		}
		result.add(yearFormat.format(p_end.getTime()));
		return result;
	}

	/**
	 * 时间比较,参数 yyyy-MM-dd HH:mm:ss 第一个时间比第二个时间早 返回true 否则返回false
	 * 
	 * @param startDate
	 *            开始时间
	 * @param endDate
	 *            结束时间
	 * @return
	 */
	public static boolean timeBefore(String startDate, String endDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date parse;
		Date parseend;
		try {
			parse = sdf.parse(startDate);
			parseend = sdf.parse(endDate);
			return parse.before(parseend);
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * String(yyyy-MM-dd HH:mm:ss) 转 Date
	 * 
	 * @param startDate
	 *            开始时间
	 * @param endDate
	 *            结束时间
	 * @return
	 */
	public static Date strToDate(String strDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date parse;
		try {
			parse = sdf.parse(strDate);

			return parse;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 时间段比较 第一个时间段比第二个时间段早 返回true 否则返回false
	 * 
	 * @param currentTime
	 * @param validTime
	 * @return
	 */
	public static boolean timeSection(String currentTime, String validTime) {

		long current = timeSplit(currentTime);
		long valid = timeSplit(validTime);
		if (current < valid) {
			return true;
		}
		return false;
	}

	private static long timeSplit(String time) {
		String[] my = time.split(":");
		int hour = Integer.parseInt(my[0]);
		int min = Integer.parseInt(my[1]);
		long totalSec = hour * 3600 + min * 60; // 秒 30180
		return totalSec;
	}

		//获取当天的开始时间
		public static java.util.Date getDayBegin() {
			Calendar cal = new GregorianCalendar();
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			return cal.getTime();
		}
		//获取当天的结束时间
		public static java.util.Date getDayEnd() {
			Calendar cal = new GregorianCalendar();
			cal.set(Calendar.HOUR_OF_DAY, 23);
			cal.set(Calendar.MINUTE, 59);
			cal.set(Calendar.SECOND, 59);
			return cal.getTime();
		}
		//获取昨天的开始时间
		public static Date getBeginDayOfYesterday() {
			Calendar cal = new GregorianCalendar();
			cal.setTime(getDayBegin());
			cal.add(Calendar.DAY_OF_MONTH, -1);
			return cal.getTime();
		}
		//获取昨天的结束时间
		public static Date getEndDayOfYesterDay() {
			Calendar cal = new GregorianCalendar();
			cal.setTime(getDayEnd());
			cal.add(Calendar.DAY_OF_MONTH, -1);
			return cal.getTime();
		}
		//获取明天的开始时间
		public static Date getBeginDayOfTomorrow() {
			Calendar cal = new GregorianCalendar();
			cal.setTime(getDayBegin());
			cal.add(Calendar.DAY_OF_MONTH, 1);

			return cal.getTime();
		}
		//获取明天的结束时间
		public static Date getEndDayOfTomorrow() {
			Calendar cal = new GregorianCalendar();
			cal.setTime(getDayEnd());
			cal.add(Calendar.DAY_OF_MONTH, 1);
			return cal.getTime();
		}
		//获取本周的开始时间
		@SuppressWarnings("unused")
		public static Date getBeginDayOfWeek() {
			Date date = new Date();
			if (date == null) {
				return null;
			}
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
			if (dayofweek == 1) {
				dayofweek += 7;
			}
			cal.add(Calendar.DATE, 2 - dayofweek);
			return getDayStartTime(cal.getTime());
		}
		//获取本周的结束时间
		public static Date getEndDayOfWeek(){
			Calendar cal = Calendar.getInstance();
			cal.setTime(getBeginDayOfWeek());
			cal.add(Calendar.DAY_OF_WEEK, 6);
			Date weekEndSta = cal.getTime();
			return getDayEndTime(weekEndSta);
		}
		//获取上周的开始时间
		@SuppressWarnings("unused")
		public static Date getBeginDayOfLastWeek() {
			Date date = new Date();
			if (date == null) {
				return null;
			}
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
			if (dayofweek == 1) {
				dayofweek += 7;
			}
			cal.add(Calendar.DATE, 2 - dayofweek - 7);
			return getDayStartTime(cal.getTime());
		}
		//获取上周的结束时间
		public static Date getEndDayOfLastWeek(){
			Calendar cal = Calendar.getInstance();
			cal.setTime(getBeginDayOfLastWeek());
			cal.add(Calendar.DAY_OF_WEEK, 6);
			Date weekEndSta = cal.getTime();
			return getDayEndTime(weekEndSta);
		}
		//获取本月的开始时间
		public static Date getBeginDayOfMonth() {
			Calendar calendar = Calendar.getInstance();
			calendar.set(getNowYear(), getNowMonth() - 1, 1);
			return getDayStartTime(calendar.getTime());
		}
		//获取本月的结束时间
		public static Date getEndDayOfMonth() {
			Calendar calendar = Calendar.getInstance();
			calendar.set(getNowYear(), getNowMonth() - 1, 1);
			int day = calendar.getActualMaximum(5);
			calendar.set(getNowYear(), getNowMonth() - 1, day);
			return getDayEndTime(calendar.getTime());
		}
		//获取上月的开始时间
		public static Date getBeginDayOfLastMonth() {
			Calendar calendar = Calendar.getInstance();
			calendar.set(getNowYear(), getNowMonth() - 2, 1);
			return getDayStartTime(calendar.getTime());
		}
		//获取上月的结束时间
		public static Date getEndDayOfLastMonth() {
			Calendar calendar = Calendar.getInstance();
			calendar.set(getNowYear(), getNowMonth() - 2, 1);
			int day = calendar.getActualMaximum(5);
			calendar.set(getNowYear(), getNowMonth() - 2, day);
			return getDayEndTime(calendar.getTime());
		}
		//获取本年的开始时间
		public static java.util.Date getBeginDayOfYear() {
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.YEAR, getNowYear());
			// cal.set
			cal.set(Calendar.MONTH, Calendar.JANUARY);
			cal.set(Calendar.DATE, 1);

			return getDayStartTime(cal.getTime());
		}
		//获取本年的结束时间
		public static java.util.Date getEndDayOfYear() {
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.YEAR, getNowYear());
			cal.set(Calendar.MONTH, Calendar.DECEMBER);
			cal.set(Calendar.DATE, 31);
			return getDayEndTime(cal.getTime());
		}
		//获取某个日期的开始时间
		public static Timestamp getDayStartTime(Date d) {
			Calendar calendar = Calendar.getInstance();
			if(null != d) calendar.setTime(d);
			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),    calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
			calendar.set(Calendar.MILLISECOND, 0);
			return new Timestamp(calendar.getTimeInMillis());
		}
		//获取某个日期的结束时间
		public static Timestamp getDayEndTime(Date d) {
			Calendar calendar = Calendar.getInstance();
			if(null != d) calendar.setTime(d);
			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),    calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
			calendar.set(Calendar.MILLISECOND, 999);
			return new Timestamp(calendar.getTimeInMillis());
		}
		//获取今年是哪一年
		public static Integer getNowYear() {
			Date date = new Date();
			GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
			gc.setTime(date);
			return Integer.valueOf(gc.get(1));
		}
		//获取本月是哪一月
		public static int getNowMonth() {
			Date date = new Date();
			GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
			gc.setTime(date);
			return gc.get(2) + 1;
		}
		//两个日期相减得到的天数
		public static int getDiffDays(Date beginDate, Date endDate) {

			if (beginDate == null || endDate == null) {
				throw new IllegalArgumentException("getDiffDays param is null!");
			}

			long diff = (endDate.getTime() - beginDate.getTime())
					/ (1000 * 60 * 60 * 24);

			int days = new Long(diff).intValue();

			return days;
		}
		//两个日期相减得到的毫秒数
		public static long dateDiff(Date beginDate, Date endDate) {
			long date1ms = beginDate.getTime();
			long date2ms = endDate.getTime();
			return date2ms - date1ms;
		}
		//获取两个日期中的最大日期
		public static Date max(Date beginDate, Date endDate) {
			if (beginDate == null) {
				return endDate;
			}
			if (endDate == null) {
				return beginDate;
			}
			if (beginDate.after(endDate)) {
				return beginDate;
			}
			return endDate;
		}
		//获取两个日期中的最小日期
		public static Date min(Date beginDate, Date endDate) {
			if (beginDate == null) {
				return endDate;
			}
			if (endDate == null) {
				return beginDate;
			}
			if (beginDate.after(endDate)) {
				return endDate;
			}
			return beginDate;
		}
		//返回某月该季度的第一个月
		public static Date getFirstSeasonDate(Date date) {
			final int[] SEASON = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 };
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int sean = SEASON[cal.get(Calendar.MONTH)];
			cal.set(Calendar.MONTH, sean * 3 - 3);
			return cal.getTime();
		}
		//返回某个日期下几天的日期
		public static Date getNextDay(Date date, int i) {
			Calendar cal = new GregorianCalendar();
			cal.setTime(date);
			cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
			return cal.getTime();
		}
		//返回某个日期前几天的日期
		public static Date getFrontDay(Date date, int i) {
			Calendar cal = new GregorianCalendar();
			cal.setTime(date);
			cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
			return cal.getTime();
		}
		//获取某年某月到某年某月按天的切片日期集合（间隔天数的集合）
		@SuppressWarnings({ "rawtypes", "unchecked" })
		public static List getTimeList(int beginYear, int beginMonth, int endYear,
									   int endMonth, int k) {
			List list = new ArrayList();
			if (beginYear == endYear) {
				for (int j = beginMonth; j <= endMonth; j++) {
					list.add(getTimeList(beginYear, j, k));

				}
			} else {
				{
					for (int j = beginMonth; j < 12; j++) {
						list.add(getTimeList(beginYear, j, k));
					}

					for (int i = beginYear + 1; i < endYear; i++) {
						for (int j = 0; j < 12; j++) {
							list.add(getTimeList(i, j, k));
						}
					}
					for (int j = 0; j <= endMonth; j++) {
						list.add(getTimeList(endYear, j, k));
					}
				}
			}
			return list;
		}
		//获取某年某月按天切片日期集合（某个月间隔多少天的日期集合）
		@SuppressWarnings({ "unchecked", "rawtypes" })
		public static List getTimeList(int beginYear, int beginMonth, int k) {
			List list = new ArrayList();
			Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1);
			int max = begincal.getActualMaximum(Calendar.DATE);
			for (int i = 1; i < max; i = i + k) {
				list.add(begincal.getTime());
				begincal.add(Calendar.DATE, k);
			}
			begincal = new GregorianCalendar(beginYear, beginMonth, max);
			list.add(begincal.getTime());
			return list;
		}

}
